<template>
    <el-dialog :title="isNew ? '创建平台': '修改平台'" :visible.sync="dialogVisible" @close="close">
        <el-form :model="form" :rules="rules" ref="platform">
            <el-form-item label="平台名称" prop="name">
                <el-input v-model="form.name"/>
            </el-form-item>
            <el-form-item label="平台首页网址" prop="url">
                <el-input v-model="form.url"/>
            </el-form-item>
            <el-form-item label="平台对应小葫芦的ID" prop="type">
                <el-input v-model="form.type"/>
            </el-form-item>
            <el-form-item>
                <el-button @click="submit" type="primary" :loading="loading">保存</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script>
    export default {
        name: "platform_edit_dialog",
        props: {
            value: Object,
            visible: Boolean,
            change: {required: true, type: Function},
        },
        data() {
            return {
                loading: false,
                isNew: true,
                dialogVisible: false,
                form: {name: '', url: '', type: ''},
                rules: {
                    name: [{required: true, message: '请填写名称', trigger: 'blur'}],
                    url: [{required: true, message: '请填写名称', trigger: 'blur'}],
                },
            };
        },
        methods: {
            submit() {
                this.$refs['platform'].validate(valid => {
                    if (!valid) return;
                    this.loading = true;
                    this.$http.post('/api/platform', this.form).then(res => {
                        this.loading = false;
                        if (this.isNew) {
                            this.$message.success('创建成功');
                            this.close();
                            this.change(res.data);
                        } else {
                            this.$message.success('修改成功');
                        }
                        this.$emit('input', this.form);
                    }).catch(err => {
                        this.loading = false;
                        this.$message.error(err.response.data);
                    });
                });
            },
            open() {
                this.dialogVisible = true;
                this.$emit('update:visible', true);
            },
            close() {
                this.dialogVisible = false;
                this.$emit('update:visible', false);
            },
        },
        watch: {
            value(val) {
                this.isNew = !val;
                if (!val) {
                    this.form = {};
                } else
                    this.form = val;
            },
            visible(val) {
                if (val)
                    this.open();
                else
                    this.close();
            }
        }
    }
</script>

<style scoped>

</style>